package net.dgg.zz.credential.generalCredential.service;

import com.alibaba.fastjson.JSONArray;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.common.util.DateUtils;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserManager;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.service.ProductService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.baseCredential.entity.BaseCredential;
import net.dgg.zz.credential.baseCredential.service.BaseCredentialService;
import net.dgg.zz.credential.capitalPoolCount.dao.CapitalPoolCountDao;
import net.dgg.zz.credential.capitalPoolCount.entity.CapitalPoolCount;
import net.dgg.zz.credential.certificateProduct.entity.CertificateProduct;
import net.dgg.zz.credential.certificateProduct.service.CertificateProductService;
import net.dgg.zz.credential.certificateSpecialty.entity.CertificateSpecialty;
import net.dgg.zz.credential.certificateSpecialty.service.CertificateSpecialtyService;
import net.dgg.zz.credential.certificateType.dao.CertificateTypeDao;
import net.dgg.zz.credential.certificateType.entity.CertificateType;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.externalFunction.entity.ProductReservation;
import net.dgg.zz.credential.externalFunction.service.ProductReservationService;
import net.dgg.zz.credential.generalCredential.dao.GeneralCertificateDao;
import net.dgg.zz.credential.generalCredential.entity.*;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import net.dgg.zz.credential.storageCapacity.service.StorageCapacityService;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.entity.UnderOder;
import net.dgg.zz.production.inProcess.dao.ProductNodeOperatingDao;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.dao.UnderOrderDao;
import net.dgg.zz.production.inProcess.entity.Assistant;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 普通证书
 *
 * @author wmj
 * @date 2018/8/21 0021
 */
@Service
public class GeneralCredentialService extends BaseService {
    @Resource
    private BaseCredentialService baseCredentialService;
    @Resource
    private SessionManager sessionManager;
    @Resource
    private ProductOrderDao productOrderDao;
    @Resource
    private StorageCapacityService storageCapacityService;
    @Resource
    private CertificateSpecialtyService certificateSpecialtyService;
    @Resource
    private GeneralCertificateDao generalCertificateDao;
    @Resource
    private ProductReservationService productReservationService;
    @Resource
    private CmsService cmsService;
    @Resource
    private SystemRecordService systemRecordService;
    @Resource
    private BaseCredentialDao baseCredentialDao;
    @Resource
    private TranslateUtil translateUtil;
    @Resource
    private CommonService commonService;
    @Resource
    private UserManager userManager;
    @Resource
    private CertificateProductService certificateProductService;
    @Resource
    private ProductService productService;
    @Resource
    private UserService userService;
    @Resource
    private ZzInProcessService zzInProcessService;
    @Resource
    private CapitalPoolCountDao capitalPoolCountDao;
    @Resource
    private CommonMangerExtService commonMangerExtService;
    @Resource
    private FlowService flowService;
    @Resource
    private ProductTimeStatusDao productTimeStatusDao;
    @Resource
    private net.dgg.zz.credential.certificateType.dao.CertificateTypeDao certificateTypeDao;
    @Resource
    private SessionManager sessionmanager;
    @Resource
    private DesUtil desUtil;
    @Resource
    private TreeBookService treeBookService;
    @Autowired
    private ProductNodeOperatingDao nodeOperatingDao;
    @Autowired
    private UnderOrderDao underOrderDao;

    public Long generalCertificateId = null;



    /**
     * 保存或者修改证书信息
     *
     * @param generalCertificate
     * @param params
     */
    @Transactional
    public List<StorageCapacity> saveOrUpdateCertificate(GeneralCertificate generalCertificate, Map params) throws ParseException, InvocationTargetException, IllegalAccessException {
        generalCertificateId = generalCertificate.getId();
        synchronized (generalCertificateId) {

            UserEntity user = sessionManager.getCurrentUser();
            GeneralCertificate generalCertificate1 =null;
            // 设置证书其他值
            if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                generalCertificate1 = generalCertificateDao.selectByPrimaryKey(generalCertificateId);
                generalCertificate.setGeneralCertificateId(generalCertificate1.getGeneralCertificateId());
            } else {
                generalCertificate.setGeneralCertificateId(DggKeyWorker.nextId());
            }

            generalCertificate.setCertificateExpiryTime(params.containsKey("certificateExpiryTimes") && StringUtils.isNotEmpty(params.get("certificateExpiryTimes")) ? DateUtils.stringToDate(params.get("certificateExpiryTimes").toString(), "yyyy-MM-dd") : null);
            generalCertificate.setCertificateToThreeTime(params.containsKey("certificateToThreeTimes") && StringUtils.isNotEmpty(params.get("certificateToThreeTimes")) ? DateUtils.stringToDate(params.get("certificateToThreeTimes").toString(), "yyyy-MM-dd") : null);
            generalCertificate.setCompanyContractExpireTime(params.containsKey("companyContractExpireTimes") && StringUtils.isNotEmpty(params.get("companyContractExpireTimes")) ? DateUtils.stringToDate(params.get("companyContractExpireTimes").toString(), "yyyy-MM-dd") : null);
            generalCertificate.setContractSigningTime(params.containsKey("contractSigningTimes") && StringUtils.isNotEmpty(params.get("contractSigningTimes")) ? DateUtils.stringToDate(params.get("contractSigningTimes").toString(), "yyyy-MM-dd") : null);
            generalCertificate.setTalentContractExpireTime(params.containsKey("talentContractExpireTimes") && StringUtils.isNotEmpty(params.get("talentContractExpireTimes")) ? DateUtils.stringToDate(params.get("talentContractExpireTimes").toString(), "yyyy-MM-dd") : null);
            generalCertificate.setDepositPayTime(params.containsKey("depositPayTimes") && StringUtils.isNotEmpty(params.get("depositPayTimes")) ? DateUtils.stringToDate(params.get("depositPayTimes").toString(), "yyyy-MM-dd HH:mm:ss") : null);
            generalCertificate.setTailMoneyPayTime(params.containsKey("tailMoneyPayTimes") && StringUtils.isNotEmpty(params.get("tailMoneyPayTimes")) ? DateUtils.stringToDate(params.get("tailMoneyPayTimes").toString(), "yyyy-MM-dd HH:mm:ss") : null);
            Map<String, String> map = baseCredentialService.dealArea(params.get("areaName").toString(), generalCertificate.getCertificateArea());
            Map<String, String> mapSocialSecurity=null;
            if (StringUtils.isNotEmpty(generalCertificate.getSocialSecurityAreaChange())){
                mapSocialSecurity = baseCredentialService.dealArea(generalCertificate.getSocialSecurityAreaChange(), generalCertificate.getSocialSecurityAreaId());
            }
            if (StringUtils.isNotEmpty(map)) { // 如果用户选择的是省/市
                generalCertificate.setAreaProvince(map.get("pcode").toString());
            } else { // 如果只选择了省
                generalCertificate.setAreaProvince(generalCertificate.getCertificateArea());
                generalCertificate.setCertificateArea(null);
            }
            // 如果用户选择的是省/市
            if (StringUtils.isNotEmpty(mapSocialSecurity)) {
                generalCertificate.setSocialSecurityArea(map.get("pcode").toString());
            } else {
                // 如果只选择了省
                generalCertificate.setSocialSecurityArea(generalCertificate.getSocialSecurityAreaId());
                generalCertificate.setSocialSecurityAreaId(null);
            }
            String certificateSpecialties = params.containsKey("certificateSpecialty") ? params.get("certificateSpecialty").toString() : null;
            Long[] certificateSpecialtys = (Long[]) ConvertUtils.convert(certificateSpecialties.split(","), Long.class);

            // 验证证书编号
            baseCredentialService.checkCredentialNo(params);

            BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(generalCertificate.getId());
            List<StorageCapacity> storageCapacities = null;
            if (StringUtils.isEmpty(baseCredential) || StringUtils.isNotEmpty(params.get("talentRenewal"))) { //新增证书
                String certificateSpecialty = params.get("certificateSpecialty").toString();
                if (!certificateSpecialty.contains(",") && StringUtils.isEmpty(params.get("talentRenewal"))){
                    int crrentCount = generalCertificateDao.getCurrentCount(params);
                    // 查询设置的证书数量
                    Integer warehousingCount = generalCertificateDao.getWarehousingCount(params);
                    if (warehousingCount != null && crrentCount >= warehousingCount) {
                        TreeBook certificateLevel = treeBookService.getTreeBookByCode(params.get("certificateLevel").toString());
                        CertificateType certificateType = certificateTypeDao.selectByPrimaryKey(Long.parseLong(certificateSpecialty));
                        ValidateUtils.isTrue(StringUtils.isNotEmpty(""), CertificateExcption.class, "抱歉，"+params.get("areaName").toString()+params.get("certificateType").toString()+"证书"+certificateLevel.getName()+"等级" +
                                ""+certificateType.getCertificateName()+"专业的证书未使用库存数量超过"+warehousingCount+"本，不允许在入库新的证书");
                    }
                }

                // 证书默认不超期
                generalCertificate.setOverdueStatus("1");

                if (null != generalCertificate.getTailMoney()) {
                    generalCertificate.setAccountMoney(generalCertificate.getDeposit().add(generalCertificate.getTailMoney()));
                }
                generalCertificate.setCertificateEntryTime(new Date());
                //电话加密
                generalCertificate.setPersonalPhone(desUtil.encrypt(generalCertificate.getPersonalPhone()));

                // 验证证书关联的生产订单状态
                ProductOrder productOrder = productOrderDao.selectByPrimaryKey(generalCertificate.getScOrderId());
                ValidateUtils.isTrue(StringUtils.isNotEmpty(productOrder) && !productOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_CERTIFICATE), CertificateExcption.class, "该销售子订单绑定的生产订单已完结，证书已经入库！");
                Product product = null;
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    // 修改证书关联销售子订单状态
                    product = productService.selectByPrimaryKey(Long.parseLong(params.get("oldProductId").toString()));
                } else {
                    product = productService.selectByPrimaryKey(Long.parseLong(params.get("productId").toString()));
                }
                product.setRelevanceCredential(1);
                ValidateUtils.isTrue(StringUtils.isNotEmpty(product), CertificateExcption.class, "该证书绑定的销售子订单不存在，请核对后进行添加！");
                productService.updateProduct(product);

                // 将资金池中销售子订单绑定的记录绑定证书
                // 将该销售子订单之前的费用申请全部绑定到现在的证书上
                List<CapitalPoolCount> list = capitalPoolCountDao.findCountByBusinessOrderId(product.getOrderBusinessId(), 1);
                if (StringUtils.isNotEmpty(list)) {
                    for (CapitalPoolCount poolCount : list) {
                        poolCount.setGeneralType(generalCertificate.getGeneralType());
                        poolCount.setBaseCertificateId(generalCertificate.getId());
                        poolCount.setCertificateNo(generalCertificate.getCertificateNo());
                        poolCount.setSignOrgId(generalCertificate.getSignOrgId());
                        poolCount.setSignOrgName(generalCertificate.getSignOrgName());
                        poolCount.setUpdaterUser(user);
                        poolCount.setIsCertificate(0);
                        capitalPoolCountDao.updateByPrimaryKeySelective(poolCount);
                    }
                }
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    // 验证证书类型并将证书绑定证书基本类型
                    storageCapacities = verificationStorageCapacityAndBoundV2(generalCertificate.getId(), params, false, generalCertificate);
                } else {
                    // 验证证书类型并将证书绑定证书基本类型
                    storageCapacities = verificationStorageCapacityAndBoundV2(generalCertificate.getId(), params, false, null);
                }

                // 证书状态：入库
                generalCertificate.setLibraryStatus(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN);
                generalCertificate.setLastWarehousingTime(new Date());

                commonService.updateScProductOrderStatus(generalCertificate.getScOrderId());
                CertificateProduct certificateProduct = certificateProductService.saveCertifateProduct(generalCertificate.getId(), generalCertificate.getScOrderId(), 1);
                // 保存操作日志
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setSource("1");
                systemRecord.setOperateType("1");
                systemRecord.setWorkTableName("zz_certificate_product");
                systemRecord.setWorkId(certificateProduct.getId());
                systemRecord.setWorkNo(certificateProduct.getScOrderNo());
                systemRecord.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecord.setSignOrgId(generalCertificate.getSignOrgId());
                systemRecord.setSignOrgName(generalCertificate.getSignOrgName());
                systemRecord.setCertificateType(generalCertificate.getCertificateType());
                systemRecord.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecord.setCertificateName(generalCertificate.getCertificateName());
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    systemRecord.setRemarks("人才续签：证书绑定生产订单");
                } else {
                    systemRecord.setRemarks("证书中心：证书绑定生产订单");
                }
                systemRecordService.save(systemRecord);

                // 证书状态默认为未使用
                generalCertificate.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);

                // 新增证书
                generalCertificate.setCreateUser(user);
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    generalCertificate.setScOrderNo(generalCertificate1.getScOrderNo());
                    generalCertificate.setScOrderId(generalCertificate1.getScOrderId());
                    baseCredentialDao.updateByPrimaryKey(generalCertificate);
                    generalCertificateDao.updateByPrimaryKey(generalCertificate);
                } else {
                    generalCertificate.setScOrderNo(null);
                    generalCertificate.setScOrderId(null);
                    baseCredentialDao.insert(generalCertificate);
                    generalCertificateDao.insert(generalCertificate);
                }


                // 保存操作日志
                SystemRecord systemRecords = new SystemRecord();
                systemRecords.setSource("1");
                systemRecords.setOperateType("1");
                systemRecords.setWorkTableName("zz_general_certificate");
                systemRecords.setWorkId(generalCertificate.getId());
                systemRecords.setWorkNo(generalCertificate.getCertificateNo());
                systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecords.setCertificateType(generalCertificate.getCertificateType());
                systemRecords.setCertificateName(generalCertificate.getCertificateName());
                systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
                systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    systemRecords.setRemarks("人才续签");
                } else {
                    systemRecords.setRemarks("证书中心：新增证书");
                }
                systemRecordService.save(systemRecords);
                // List<Node> nodeList = flowService.getNode(productOrder.getId());
                ProductTimeStatus productTimeStatus = productTimeStatusDao.selectByPrimaryKey(productOrder.getId());
                if(null != productTimeStatus.getNodeEndTime() && !StringUtils.isEmpty(productOrder.getFlowContent())){
                        Node  node = flowService.queyNodeListByName("证书入库",productOrder.getId());
                        if(null != node.getName()) {
                            UserEntity currentUser = sessionmanager.getCurrentUser();
                            Map currentMap = this.commonMangerExtService.findOrg(currentUser.getOrgId());
                            if (null != currentMap) {
                                productOrder.setFlowUserId(currentUser.getId());
                                productOrder.setFlowUserName(currentUser.getRealName().concat(currentUser.getLoginName()));
                                productOrder.setFlowUserOrgId(Long.valueOf(currentMap.get("id").toString()));
                                productOrder.setFlowUserOrgName(currentMap.get("name").toString());
                            }
                            int a = net.dgg.zz.common.utils.DateUtils.compare_date(new Date(), productTimeStatus.getNodeEndTime());
                            if (a == 1 && 1 == node.getIsPunish()) {
                                zzInProcessService.nodeTimeOutPunish(productOrder, node, productTimeStatus);
                            }
                        }
                }
                StringBuilder msgContent=new StringBuilder();
                msgContent.append("您好，您的客户"+productOrder.getCustomerName()+"订单"+productOrder.getOrderNo()+"【"+productOrder.getScProductOrderNo()+"收证");
                msgContent.append(",证书已入库，请知晓");
                commonService.sendQgjMessage(productOrder.getOrderId(),productOrder.getBusinessTypeCode(),user.getId(),user.getRealName(),user.getLoginName(),msgContent.toString());
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(productOrder.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(productOrder.getId());
                customerRecord.setTableNo(productOrder.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE22);
                customerRecord.setCreaterId(user.getId());
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    customerRecord.setContent("人才续签");
                } else {
                    customerRecord.setContent("证书中心：新增证书");
                }
                MQMessageSendUtil.ucMessageSend(customerRecord);
            } else {
                GeneralCertificate oldGeneralCertificate = generalCertificateDao.selectByPrimaryKey(generalCertificate.getId());
                GeneralCertificate newGeneralCertificate = new GeneralCertificate();
                BeanUtils.copyProperties(newGeneralCertificate, oldGeneralCertificate);
                String overdueStatus = oldGeneralCertificate.getOverdueStatus();
                newGeneralCertificate.setIsTalentAppearanceCoordinate(generalCertificate.getIsTalentAppearanceCoordinate());
                newGeneralCertificate.setIsTalentOriginalCopyCoordinate(generalCertificate.getIsTalentOriginalCopyCoordinate());
                newGeneralCertificate.setSpecialNote(generalCertificate.getSpecialNote());
                newGeneralCertificate.setCertificateExpiryTime(generalCertificate.getCertificateExpiryTime());
                newGeneralCertificate.setCertificateToThreeTime(generalCertificate.getCertificateToThreeTime());
                newGeneralCertificate.setCompanyContractExpireTime(generalCertificate.getCompanyContractExpireTime());
                newGeneralCertificate.setContractSigningTime(generalCertificate.getContractSigningTime());
                newGeneralCertificate.setTalentContractExpireTime(generalCertificate.getTalentContractExpireTime());

                newGeneralCertificate.setUpdaterUser(user);
                // 地区
                newGeneralCertificate.setAreaProvince(generalCertificate.getAreaProvince());
                newGeneralCertificate.setCertificateArea(generalCertificate.getCertificateArea());
                // 证书编号
                newGeneralCertificate.setCertificateNo(generalCertificate.getCertificateNo());
                // 证书级别
                newGeneralCertificate.setCertificateLevel(generalCertificate.getCertificateLevel());
                // 证书适用范围
                newGeneralCertificate.setApplicationScope(generalCertificate.getApplicationScope());
                // 三类证书
                newGeneralCertificate.setCertificateToThree(generalCertificate.getCertificateToThree());
                // 回收价格
                newGeneralCertificate.setReceiptPrice(generalCertificate.getReceiptPrice());
                // 类别
                newGeneralCertificate.setCertificateCategory(generalCertificate.getCertificateCategory());
                // 证书名称
                newGeneralCertificate.setCertificateName(generalCertificate.getCertificateName());
                // 是否代签
                newGeneralCertificate.setIsWhetherSign(generalCertificate.getIsWhetherSign());
                // 持证人
                newGeneralCertificate.setPersonalName(generalCertificate.getPersonalName());
                // 持证人身份证号码
                newGeneralCertificate.setPersonalIdCard(generalCertificate.getPersonalIdCard());
                // 持证人电话
                String oldPersonalPhone =  net.dgg.iboss.base.util.StringUtils.encryptionNumber(desUtil.decrypt(oldGeneralCertificate.getPersonalPhone()));
                String newPersonalPhone = generalCertificate.getPersonalPhone();
                if(!oldPersonalPhone.equals(newPersonalPhone)) {
                    newGeneralCertificate.setPersonalPhone(desUtil.encrypt(generalCertificate.getPersonalPhone()));
                }
                // 是否购买社保
                newGeneralCertificate.setSocialSecurity(generalCertificate.getSocialSecurity());
                // 社保地区
                newGeneralCertificate.setSocialSecurityAreaChange(generalCertificate.getSocialSecurityAreaChange());
                // 社保市级地区
                newGeneralCertificate.setSocialSecurityAreaId(generalCertificate.getSocialSecurityAreaId());
                // 社保升级id
                newGeneralCertificate.setSocialSecurityArea(generalCertificate.getSocialSecurityArea());
                // 人才付款方式
                newGeneralCertificate.setTalentPaymentMethod(generalCertificate.getTalentPaymentMethod());
                // 收证类型
                newGeneralCertificate.setReceiptType(generalCertificate.getReceiptType());
                // 渠道名称
                newGeneralCertificate.setChannelName(generalCertificate.getChannelName());
                // 渠道dianhua
                newGeneralCertificate.setChannelPhone(generalCertificate.getChannelPhone());
                // 渠道身份证号
                newGeneralCertificate.setChannelIdCard(generalCertificate.getChannelIdCard());
                // 持证人微信
                newGeneralCertificate.setPersonalWeixin(generalCertificate.getPersonalWeixin());
                // 收款户名
                newGeneralCertificate.setAccountName(generalCertificate.getAccountName());
                // 开户行
                newGeneralCertificate.setAccountBank(generalCertificate.getAccountBank());
                // 收款账号
                newGeneralCertificate.setAccountNo(generalCertificate.getAccountNo());
                // 资格证书
                newGeneralCertificate.setIsQuelificationCertificate(generalCertificate.getIsQuelificationCertificate());
                // 毕业证
                newGeneralCertificate.setIsGraduationCertificate(generalCertificate.getIsGraduationCertificate());
                // 信息卡
                newGeneralCertificate.setIsInformationCard(generalCertificate.getIsInformationCard());
                // 合同编号
                newGeneralCertificate.setContractNo(generalCertificate.getContractNo());
                // 收证商务名称
                newGeneralCertificate.setCollectorName(generalCertificate.getCollectorName());
                // 收证商务id
                newGeneralCertificate.setCollectorId(generalCertificate.getCollectorId());
                // 集团归档
                newGeneralCertificate.setIsGroupFiling(generalCertificate.getIsGroupFiling());
                if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(newGeneralCertificate.getCertificateStatus())) {
                    newGeneralCertificate.setScOrderNo(null);
                    newGeneralCertificate.setScOrderId(null);
                }
                //使用修改
                newGeneralCertificate.setAffiliatedCompany(params.get("affiliatedCompany") == null ? "" : params.get("affiliatedCompany").toString());

                if (StringUtils.isNotEmpty(params.get("affiliatedStartTimes"))) {
                    newGeneralCertificate.setAffiliatedStartTime(DateUtil.stringToDate(params.get("affiliatedStartTimes").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                } else {
                    newGeneralCertificate.setAffiliatedStartTime(null);
                }
                if (StringUtils.isNotEmpty(params.get("affiliatedExpireTimes"))) {
                    newGeneralCertificate.setAffiliatedExpireTime(DateUtil.stringToDate(params.get("affiliatedExpireTimes").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                } else {
                    newGeneralCertificate.setAffiliatedExpireTime(null);
                }
                newGeneralCertificate.setThreeAffiliatedCompany(params.get("threeAffiliatedCompany") == null ? "" : params.get("threeAffiliatedCompany").toString());
                if (StringUtils.isNotEmpty(params.get("threeAffiliatedStartTimes"))) {
                    newGeneralCertificate.setThreeAffiliatedStartTime(DateUtil.stringToDate(params.get("threeAffiliatedStartTimes").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                } else {
                    newGeneralCertificate.setThreeAffiliatedStartTime(null);
                }
                if (StringUtils.isNotEmpty(params.get("threeAffiliatedExpireTimes"))) {
                    newGeneralCertificate.setThreeAffiliatedExpireTime(DateUtil.stringToDate(params.get("threeAffiliatedExpireTimes").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                } else {
                    newGeneralCertificate.setThreeAffiliatedExpireTime(null);
                }

                Date date = new Date();
                // 判断证书超期
                Boolean certificateToThreeTimeOverDue = (StringUtils.isNotEmpty(newGeneralCertificate.getCertificateToThreeTime()) && (DateUtil.daysBetween(newGeneralCertificate.getCertificateToThreeTime(), date) > 0)) ? false : true;
                Boolean certificateExpiryTimeOverDue = StringUtils.isNotEmpty(newGeneralCertificate.getCertificateExpiryTime()) && DateUtil.daysBetween(newGeneralCertificate.getCertificateExpiryTime(), date) > 0 ? false : true;
                Boolean talentContractExpireTimeOverDue = StringUtils.isNotEmpty(newGeneralCertificate.getTalentContractExpireTime()) && DateUtil.daysBetween(newGeneralCertificate.getTalentContractExpireTime(), date) > 0 ? false : true;
                Boolean companyContractExpireTimeOverDue = StringUtils.isNotEmpty(newGeneralCertificate.getCompanyContractExpireTime()) && DateUtil.daysBetween(newGeneralCertificate.getCompanyContractExpireTime(), date) > 0 ? false : true;
                Boolean affiliatedExpireTimeOverDue = StringUtils.isNotEmpty(newGeneralCertificate.getAffiliatedExpireTime()) && DateUtil.daysBetween(newGeneralCertificate.getAffiliatedExpireTime(), date) > 0 ? false : true;
                Boolean threeAffiliatedExpireTimeOverDue = StringUtils.isNotEmpty(generalCertificate.getThreeAffiliatedExpireTime()) && DateUtil.daysBetween(generalCertificate.getThreeAffiliatedExpireTime(), date) > 0 ? false : true;

                if (certificateToThreeTimeOverDue && certificateExpiryTimeOverDue && talentContractExpireTimeOverDue && companyContractExpireTimeOverDue && affiliatedExpireTimeOverDue) {
                    newGeneralCertificate.setOverdueType(null);
                    newGeneralCertificate.setOverdueStatus("1");
                } else {
                    StringBuffer overDueType = new StringBuffer();
                    newGeneralCertificate.setOverdueStatus("0");
                    // 证书超期或者三类证书超期
                    if (!certificateToThreeTimeOverDue || !certificateExpiryTimeOverDue) {
                        overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL + ",");
                    }
                    if (!talentContractExpireTimeOverDue) { // 人才合同到期
                        overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_TALENTS + ",");
                    }
                    if (!companyContractExpireTimeOverDue) { // 企业合同到期
                        overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_COMPANY + ",");
                    }

                    if (!affiliatedExpireTimeOverDue || !threeAffiliatedExpireTimeOverDue) { // 使用超期
                        overDueType.append(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_AFFILIATED + ",");
                    }
                    newGeneralCertificate.setOverdueType(overDueType.toString());
                }

                // 修改证书信息
                baseCredentialDao.updateByPrimaryKey(newGeneralCertificate);
                generalCertificateDao.updateByPrimaryKey(newGeneralCertificate);
                // 验证证书类型并将证书绑定证书基本类型
                storageCapacities = verificationStorageCapacityAndBoundV2(newGeneralCertificate.getId(), params, false, oldGeneralCertificate);

                // 保存操作日志
                SystemRecord systemRecords = new SystemRecord();
                systemRecords.setSource("1");
                systemRecords.setOperateType("2");
                systemRecords.setWorkTableName("zz_general_certificate");
                systemRecords.setWorkId(generalCertificate.getId());
                systemRecords.setWorkNo(generalCertificate.getCertificateNo());
                systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
                systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
                systemRecords.setCertificateType(generalCertificate.getCertificateType());
                systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
                systemRecords.setCertificateName(generalCertificate.getCertificateName());
                if (StringUtils.isNotEmpty(params.get("talentRenewal"))){
                    systemRecords.setRemarks("人才续签");
                } else {
                    systemRecords.setRemarks("证书中心：修改证书");
                }
                systemRecordService.save(systemRecords);
            }
            return storageCapacities;
        }
    }

    /**
     * 《已废弃》
     * 验证证书类型并且绑定中间表
     *
     * @param params
     * @param id       证书id
     * @param isReback 是否是退回证书：退回证书库容量不需要减1，可以做是否减去老的专业库容量
     */
    @Transactional
    public List<StorageCapacity> verificationStorageCapacityAndBound(Long id, Map params, Boolean isReback) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
        // 验证证书专业是否已经绑定证书基础类型
        List<StorageCapacity> allList = storageCapacityService.verificationStorageCapacity(params);
        if (StringUtils.isNotEmpty(allList) && allList.size() > 0) {

            // 查询证书是否已经绑定了证书专业
            List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(id);
            if (StringUtils.isNotEmpty(certificateSpecialties) && certificateSpecialties.size() > 0) {
                // 删除以前的证书专业中间表数据
                List<String> codes = new ArrayList<>();
                for (CertificateSpecialty certificateSpecialty : certificateSpecialties) {
                    codes.add(certificateSpecialty.getCertificateCode());
                }
                // 查询以前绑定的基本类型的信息
                List<StorageCapacity> storageCapacitysByCodes = storageCapacityService.findStorageCapacitysByCodes(codes);
                if (!isReback) {
                    // 将以前专业的库容量-1
                    for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                        storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers() - 1);
                    }
                    storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                }

                // 删除证书绑定的证书专业中间表数据
                certificateSpecialtyService.deleteByCertificateId(id);
                allList = storageCapacityService.findStorageCapacitys(params);
            }
            CertificateSpecialty certificateSpecialty = null;
            for (StorageCapacity storageCapacity : allList) {
                certificateSpecialty = new CertificateSpecialty();
                certificateSpecialty.setCertificateCode(storageCapacity.getCertificateCode());
                certificateSpecialty.setCertificateSpecialtyId(storageCapacity.getCertificateMajorId());
                certificateSpecialty.setCertificateTypeId(storageCapacity.getCertificateTypeId());
                certificateSpecialty.setCertificateId(id);
                certificateSpecialty.setId(DggKeyWorker.nextId());
                certificateSpecialty.setType(params.containsKey("generalType") && params.get("generalType").toString().equals(CredentialConstant.ZZ_CREDENTIAL) ? CredentialConstant.ZZ_CREDENTIAL : CredentialConstant.GENERAL_CREDENTIAL);
                certificateSpecialtyService.insert(certificateSpecialty);
            }
            // 修改库容 在库容量+1
            for (StorageCapacity storageCapacity : allList) {
                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
            }

            storageCapacityService.updateStorageCapacityCount(allList);
        }
        return allList;
    }

    /**
     * 证书预约绑定
     * 查询指定证书类型是否有生产订单预约
     *
     * @param certificateId          证书id
     * @param storageCapacities      证书基本类型List
     * @param isChangeLibraryNumbers 是否需要改变在库可用容量
     */
    @Transactional
    public BaseCredential boundProductReservation(Long certificateId, List<StorageCapacity> storageCapacities, Boolean isChangeLibraryNumbers) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(certificateId) || StringUtils.isNotEmpty(storageCapacities) || isChangeLibraryNumbers, CertificateExcption.class, "参数不能为空!");
        UserEntity user = sessionManager.getCurrentUser();
        BaseCredential baseCredential = baseCredentialService.selectByPrimaryKey(certificateId);

        // 查询预约
        List<String> storageCapacityCode = new ArrayList<>();
        for (StorageCapacity storageCapacity : storageCapacities) {
            storageCapacityCode.add(storageCapacity.getCertificateCode());
        }

        // 查询需要更改预约状态的生产订单证书预约数据
        List<ProductReservation> productReservations = productReservationService.queryReservationByStorageCapacity(storageCapacityCode, CredentialConstant.PRODUCT_RESERVATION_STATUS_RESERVATION);
        String storageCapacityCodes = null;

        //需要修改库容的证书基本类型
        List<StorageCapacity> newStorageCapacity = null;
        if (StringUtils.isNotEmpty(productReservations) && productReservations.size() > 0) { // 如果有证书预约的话
            newStorageCapacity = new ArrayList<>();
            for (ProductReservation productReservation : productReservations) {
                productReservation.setStatus(CredentialConstant.PRODUCT_RESERVATION_STATUS_SUCCESS);
                productReservation.setCertificateId(baseCredential.getId());
                productReservation.setUpdaterUser(user);
                // 修改证书预约
                productReservationService.updateReservation(productReservation);

                // 保存操作日志
                SystemRecord systemRecord = new SystemRecord();
                systemRecord.setSource("1");
                systemRecord.setOperateType("2");
                systemRecord.setWorkTableName("zzsc_product_reservation");
                systemRecord.setWorkId(productReservation.getId());
                systemRecord.setWorkNo(productReservation.getScProductNo());
                systemRecord.setCertificateCode(baseCredential.getCertificateNo());
                systemRecord.setSignOrgId(baseCredential.getSignOrgId());
                systemRecord.setSignOrgName(baseCredential.getSignOrgName());
                systemRecord.setCertificateType(baseCredential.getCertificateType());
                systemRecord.setRemarks("证书中心：修改证书预约状态");
                systemRecordService.save(systemRecord);


                CertificateProduct certificateProduct = certificateProductService.saveCertifateProduct(baseCredential.getId(), productReservation.getScProductId(), 1);
                // 保存操作日志
                SystemRecord systemRecords = new SystemRecord();
                systemRecords.setSource("1");
                systemRecords.setOperateType("10");
                systemRecords.setWorkTableName("zz_certificate_product");
                systemRecords.setWorkId(certificateProduct.getId());
                systemRecords.setWorkNo(certificateProduct.getScOrderNo());
                systemRecords.setCertificateCode(baseCredential.getCertificateNo());
                systemRecords.setSignOrgId(baseCredential.getSignOrgId());
                systemRecords.setSignOrgName(baseCredential.getSignOrgName());
                systemRecords.setCertificateType(baseCredential.getCertificateType());
                systemRecords.setCertificateCode(baseCredential.getCertificateNo());
                systemRecords.setCertificateName(baseCredential.getCertificateName());
                systemRecords.setRemarks("证书中心：证书绑定预约该证书的生产订单");
                systemRecordService.save(systemRecords);

                for (StorageCapacity storageCapacity : storageCapacities) {
                    if (storageCapacity.getCertificateCode().equals(productReservation.getCertificateNo())) {
                        // 预约量 - 1
                        storageCapacity.setOrderNumbers(storageCapacity.getOrderNumbers() - 1);
                    }
                    // 预订量 + 1
                    storageCapacity.setReserveNumbers(storageCapacity.getReserveNumbers() + 1);
                    // 在库 -1
                    storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() - 1);
                    newStorageCapacity.add(storageCapacity);
                }

            }

            // 证书和资质状态修改为已预订
            if (baseCredential.getGeneralType().equals(CredentialConstant.GENERAL_CREDENTIAL)) {
                baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION);
            } else if (baseCredential.getGeneralType().equals(CredentialConstant.ZZ_CREDENTIAL)) {
                baseCredential.setCertificateStatus(CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO);
            }

            if (StringUtils.isNotEmpty(productReservations) && productReservations.size() > 0) {
                // 证书{0}已经于{1}由{2}成功预订
                String[] msgs = new String[]{baseCredential.getCertificateNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"), productReservations.get(0).getScProductNo()};
                String[] codes = null;
                if (baseCredential.getGeneralType().equals(CredentialConstant.GENERAL_CREDENTIAL)) {
                    codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                } else if (baseCredential.getGeneralType().equals(CredentialConstant.ZZ_CREDENTIAL)) {
                    codes = new String[]{"ZZSC_ZZ_ADMIN", "ZZSC_ZZ_SUPER_ADMIN"};
                }
                List<UserEntity> users = userService.findUserByRoleCodesAndOrgs(codes, 0, baseCredential.getSignOrgId());
                ProductOrder productOrder = productOrderDao.selectByPrimaryKey(productReservations.get(0).getScProductId());
                List<Assistant> assistants = zzInProcessService.queyScAssistantList(productOrder.getId());//协单人员
                UserEntity assistUser;
                for (Assistant assistant : assistants) {
                    assistUser = new UserEntity();
                    assistUser.setId(assistant.getAssistUserId());
                    users.add(assistUser);
                }
                if (StringUtils.isNotEmpty(productOrder.getFlowUserId())) {
                    // 流程人员
                    UserEntity flewUser = userService.findUserById(productOrder.getFlowUserId());
                    users.add(flewUser);
                }
                if (baseCredential.getGeneralType().equals(CredentialConstant.GENERAL_CREDENTIAL)) {
                    commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZS_RESERVATION");//证书预定模板
                } else if (baseCredential.getGeneralType().equals(CredentialConstant.ZZ_CREDENTIAL)) {
                    commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_ZZ_RESERVATION");//资质预定模板
                }
                baseCredential.setScOrderId(productReservations.get(0).getScProductId());
                baseCredential.setScOrderNo(productReservations.get(0).getScProductNo());
            }
            storageCapacityService.updateStorageCapacityCount(newStorageCapacity);

            baseCredentialDao.updateByPrimaryKeySelective(baseCredential);

            SystemRecord record = new SystemRecord();
            record.setSource("1");
            record.setOperateType("2");
            record.setWorkTableName("zz_general_certificate");
            record.setWorkId(baseCredential.getId());
            record.setWorkNo(baseCredential.getCertificateNo());
            record.setCertificateType(baseCredential.getCertificateType());
            record.setCertificateCode(baseCredential.getCertificateNo());
            record.setCertificateName(baseCredential.getCertificateName());
            record.setSignOrgId(baseCredential.getSignOrgId());
            record.setSignOrgName(baseCredential.getSignOrgName());
            record.setRemarks("证书中心：修改证书状态为已预订");
            systemRecordService.save(record);

            return baseCredential;

        } else { // 没有预约
            if (isChangeLibraryNumbers) {
                // 修改库容 在库容量+1
                for (StorageCapacity storageCapacity : storageCapacities) {
                    storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                }
                storageCapacityService.updateStorageCapacityCount(storageCapacities);
            }

        }
        return null;
    }

    /**
     * 查询证书列表信息并分页
     *
     * @param params
     * @return
     */
    public List<GeneralCertificate> queryGertificateInfo(Map params) {
        // (1不区分事业部，0按用户事业部搜索，2按用户事业部地区搜索，3按订单签单事业部地区搜索)
        if (params.containsKey("isAll")) {
            if(params.get("isAll").equals("1")){

            }
            if(params.get("isAll").equals("0")){
                params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
            }
            if(params.get("isAll").equals("2")){
                params.put("placeCode", commonService.findUserArea(sessionManager.getCurrentUser()));
            }
            if(params.get("isAll").equals("3") && StringUtils.isNotEmpty(params.get("scOrderId"))){
                ProductOrder scOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(params.get("scOrderId").toString()));
                params.remove("scOrderId");
                params.put("placeCode", commonService.findOrgArea(scOrder.getSignOrgId()));
            }
        }
        if (params.containsKey("areaName1") ) {
            params.put("areaName", params.get("areaName1").toString());
        }
        params.put("returnStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        if(params.containsKey("personalPhone") && !StringUtils.isEmpty(params.get("personalPhone"))) {
            params.put("personalPhone", desUtil.encrypt(params.get("personalPhone").toString()));
        }
        if(params.containsKey("personalPhone1") && !StringUtils.isEmpty(params.get("personalPhone1"))) {
            params.put("personalPhone1", desUtil.encrypt(params.get("personalPhone1").toString()));
        }
        if (null != params.get("matchNumber")) {
            String matchNumberStr = (String) params.get("matchNumber");
            TreeBook treeBookByCode = treeBookService.getTreeBookByCode("matchNumber");
            Long matchNumber = Long.parseLong(matchNumberStr) * Long.parseLong(treeBookByCode.getExt1());
            params.put("matchNumber",matchNumber);
        }
        List<GeneralCertificate> generalCertificates = generalCertificateDao.queryGertificateInfoWithPage(params);
        String[] column = {"certificateCategory", "libraryStatus", "certificateStatus", "overdueType", "certificateArea", "areaProvince", "certificateStatus", "applicationScope", "certificateLevel", "certificateToThree"};
        generalCertificates = translateUtil.translateList(column, generalCertificates);
        return generalCertificates;
    }

    /**
     * 查询证书列表信息并分页2
     *
     * @param params
     * @return
     */
    public List<GeneralCertificate> queryGertificateInfo2(Map params) {
        // (1不区分事业部，0按用户事业部搜索，2按用户事业部地区搜索，3按订单签单事业部地区搜索)
        if (params.containsKey("isAll")) {
            if(params.get("isAll").equals("1")){

            }
            if(params.get("isAll").equals("0")){
                params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
            }
            if(params.get("isAll").equals("2")){
                params.put("placeCode", commonService.findUserArea(sessionManager.getCurrentUser()));
            }
            if(params.get("isAll").equals("3") && StringUtils.isNotEmpty(params.get("scOrderId"))){
                ProductOrder scOrder = productOrderDao.selectByPrimaryKey(Long.valueOf(params.get("scOrderId").toString()));
                params.remove("scOrderId");
                params.put("placeCode", commonService.findOrgArea(scOrder.getSignOrgId()));
            }
        }
        if (params.containsKey("areaName1") ) {
            params.put("areaName", params.get("areaName1").toString());
        }
        params.put("returnStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        if(params.containsKey("personalPhone") && !StringUtils.isEmpty(params.get("personalPhone"))) {
            params.put("personalPhone", desUtil.encrypt(params.get("personalPhone").toString()));
        }
        if(params.containsKey("personalPhone1") && !StringUtils.isEmpty(params.get("personalPhone1"))) {
            params.put("personalPhone1", desUtil.encrypt(params.get("personalPhone1").toString()));
        }
        if (null != params.get("matchNumber")) {
            String matchNumberStr = (String) params.get("matchNumber");
            TreeBook treeBookByCode = treeBookService.getTreeBookByCode("matchNumber");
            Long matchNumber = Long.parseLong(matchNumberStr) * Long.parseLong(treeBookByCode.getExt1());
            params.put("matchNumber",matchNumber);
        }
        List<GeneralCertificate> generalCertificates = generalCertificateDao.queryGertificateInfo2(params);
        String[] column = {"certificateCategory", "libraryStatus", "certificateStatus", "overdueType", "certificateArea", "areaProvince", "certificateStatus", "applicationScope", "certificateLevel", "certificateToThree"};
        generalCertificates = translateUtil.translateList(column, generalCertificates);
        return generalCertificates;
    }

//    /**
//     * 查询证书预匹配结果
//     *
//     */
//    public List<GeneralCertificate> queryGertificateAdvanceMatchResult(Map params){
//        List<GeneralCertificate> generalCertificates = generalCertificateDao.queryGertificateInfo2(params);
//        String[] column = {"certificateCategory", "libraryStatus", "certificateStatus", "overdueType", "certificateArea", "areaProvince", "certificateStatus", "applicationScope", "certificateLevel", "certificateToThree"};
//        generalCertificates = translateUtil.translateList(column, generalCertificates);
//        return generalCertificates;
//    }

    /**
     * 查询需要导出的证书信息
     *
     * @param params
     * @return
     */
    public List<GeneralCredentialVo> queryExportCredential(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if(params.containsKey("personalPhone") && !StringUtils.isEmpty(params.get("personalPhone"))) {
            params.put("personalPhone", desUtil.encrypt(params.get("personalPhone").toString()));
        }
        params.put("returnStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        List<GeneralCredentialVo> generalCertificates = generalCertificateDao.queryExportCredential(params);
        String[] column = {"certificateCategory", "libraryStatus", "certificateStatus", "overdueType", "certificateArea", "areaProvince", "certificateStatus", "applicationScope", "certificateLevel"};
        generalCertificates = translateUtil.translateList(column, generalCertificates);
        return generalCertificates;
    }

    /*
     * @Author zsx
     * @Date 2018-08-27 06:08:52
     * @Description 分页查询退回证书列表
     * @param params
     * @return List<Map>
     */
    public List<GeneralCertificate> selectReturnCertificateByWithPage(Map<String, Object> params) {
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");
            params.put("orderColumn", "g.last_outgoing_time");
        }
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        params.put("libraryStatus", CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT);
        params.put("outgoingReason", CredentialConstant.OUT_GOING_REASON_TALENT_RETURN);
        params.put("generalCredentialStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        List<GeneralCertificate> certificates = generalCertificateDao.selectReturnCertificateByWithPage(params);
        String[] column = {"certificateCategory", "libraryStatus", "certificateArea", "applicationScope", "areaProvince", "certificateLevel"};
        return translateUtil.translateList(column, certificates);
    }

    /*
     * @Author zsx
     * @Date 2018-08-28 10:08:00
     * @Description 查询需要导出的退回证书
     */
    public List<ReturnCertificateVo> selectExportRetenCredential(Map<String, Object> params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        params.put("libraryStatus", CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT);
        params.put("outgoingReason", CredentialConstant.OUT_GOING_REASON_TALENT_RETURN);
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        String[] column = {"certificateCategory", "certificateArea", "areaProvince", "applicationScope", "certificateLevel", "certificateStatus"};
        List<ReturnCertificateVo> returnCertificateVos = generalCertificateDao.selectExportRetenCredential(params);
        return translateUtil.translateList(column, returnCertificateVos);
    }

    /**
     * 查询证书出入库状态
     *
     * @param id
     * @param generalCredentialLibraryStatus
     */
    public GeneralCertificate checkCredentialStatus(Long id, String generalCredentialLibraryStatus) {
        GeneralCertificate generalCertificate = generalCertificateDao.selectByPrimaryKey(id);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(generalCertificate), CertificateExcption.class, " 证书不存在！");

        ValidateUtils.isTrue(StringUtils.isEmpty(generalCertificate.getLibraryStatus()) || generalCertificate.getLibraryStatus().equals(generalCredentialLibraryStatus), CertificateExcption.class, "证书已经进行过出库或者入库操作，请刷新页面进行核对！");
        return generalCertificate;
    }

    /**
     * 证书出库
     *
     * @param generalCertificate
     * @param params
     */
    @Transactional
    public void credentialGetOut(GeneralCertificate generalCertificate, Map params) {
        UserEntity currentUser = sessionManager.getCurrentUser();
        generalCertificate.setLibraryStatus(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT);
        generalCertificate.setOutgoingReason(params.containsKey("outgoingReason") && StringUtils.isNotEmpty("outgoingReason") ? params.get("outgoingReason").toString() : null);
        generalCertificate.setOutboundDataType(params.containsKey("outboundDataType") && StringUtils.isNotEmpty("outboundDataType") ? params.get("outboundDataType").toString() : null);
        generalCertificate.setLastWarehousingTime(params.containsKey("lastWarehousingTime") && StringUtils.isNotEmpty("lastWarehousingTime") ? DateUtils.stringToDate(params.get("lastWarehousingTime").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setRemarks(params.containsKey("remarks") && StringUtils.isNotEmpty("remarks") ? params.get("remarks").toString() : null);
        generalCertificate.setUpdaterUser(currentUser);
        generalCertificate.setOutgoingOperater(currentUser);
        UserEntity user = null;
        if (params.containsKey("certificateUserId") && StringUtils.isNotEmpty(params.get("certificateUserId"))) {
            user = (UserEntity) userManager.findUserById(Long.parseLong(params.get("certificateUserId").toString()));
        }

        generalCertificate.setCertificateUser(user);
        Map org = commonMangerExtService.findOrg(user.getOrgId());
        if (null != org) {
            generalCertificate.setCertificateUserOrgId(Long.parseLong(org.get("id").toString()));
            generalCertificate.setCertificateUserOrgName(org.get("name").toString());
        }


        generalCertificateDao.updateByPrimaryKeySelective(generalCertificate);

        BaseCredential baseCredential = baseCredentialDao.selectByPrimaryKey(generalCertificate.getId());
        // 如果是退回人才
        if (generalCertificate.getOutgoingReason().equals(CredentialConstant.OUT_GOING_REASON_TALENT_RETURN)) {
            baseCredential.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        }
        baseCredential.setUpdaterUser(currentUser);
        baseCredential.setRemarks(generalCertificate.getRemarks());
        baseCredentialDao.updateByPrimaryKeySelective(baseCredential);
        // 如果证书状态为未使用并且未过期则需要修改库容量 证书过期类型不是证书过期也需要减库容
        if ((generalCertificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE) && "1".equals(generalCertificate.getOverdueStatus())) || (generalCertificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE) && "0".equals(generalCertificate.getOverdueStatus()) && !generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
            List<StorageCapacity> storageCapacities = storageCapacityService.findStorageCapacityByCertificateId(generalCertificate.getId());
            for (StorageCapacity storageCapacity : storageCapacities) {
                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() - 1);
            }
            storageCapacityService.updateStorageCapacityCount(storageCapacities);
        }

        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("7");
        record.setWorkTableName("zz_general_certificate");
        record.setWorkId(generalCertificate.getId());
        record.setWorkNo(generalCertificate.getCertificateNo());
        record.setCertificateName(generalCertificate.getCertificateName());
        record.setCertificateCode(generalCertificate.getCertificateNo());
        record.setSignOrgId(generalCertificate.getSignOrgId());
        record.setSignOrgName(generalCertificate.getSignOrgName());
        record.setCertificateType(generalCertificate.getCertificateType());
        record.setRemarks("证书中心：" + generalCertificate.getCertificateNo() + "出库");
        systemRecordService.save(record);
    }

    /**
     * 入库
     *
     * @param generalCertificate
     * @param params
     */
    public void credentialGetIn(GeneralCertificate generalCertificate, Map params) {
        UserEntity currentUser = sessionManager.getCurrentUser();
        generalCertificate.setLibraryStatus(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN);
        generalCertificate.setWarehousingReason(params.containsKey("warehousingReason") && StringUtils.isNotEmpty("warehousingReason") ? params.get("warehousingReason").toString() : null);
        generalCertificate.setRemarks(params.containsKey("remarks") && StringUtils.isNotEmpty("remarks") ? params.get("remarks").toString() : null);
        generalCertificate.setRemarks(params.containsKey("remarks") && StringUtils.isNotEmpty("remarks") ? params.get("remarks").toString() : null);
        generalCertificate.setUpdaterUser(currentUser);
        UserEntity user = null;
        if (params.containsKey("certificateUserId") && StringUtils.isNotEmpty(params.get("certificateUserId"))) {
            user = (UserEntity) userManager.findUserById(Long.parseLong(params.get("certificateUserId").toString()));
        }
        generalCertificate.setWarehousingOperater(user);
        generalCertificate.setLastWarehousingTime(new Date());
        generalCertificateDao.updateByPrimaryKeySelective(generalCertificate);

        BaseCredential baseCredential = baseCredentialDao.selectByPrimaryKey(generalCertificate.getId());
        baseCredential.setUpdaterUser(currentUser);
        baseCredential.setRemarks(generalCertificate.getRemarks());
        baseCredentialDao.updateByPrimaryKeySelective(baseCredential);

        // 如果证书状态为未使用并且未过期则需要修改库容量  或者证书超期但是超期状态不包含证书过期的需要修改库容
        if ((generalCertificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE) && "1".equals(generalCertificate.getOverdueStatus())) || (generalCertificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE) && "0".equals(generalCertificate.getOverdueStatus()) && !generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL))) {
            List<StorageCapacity> storageCapacities = storageCapacityService.findStorageCapacityByCertificateId(generalCertificate.getId());
            for (StorageCapacity storageCapacity : storageCapacities) {
                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
            }
            storageCapacityService.updateStorageCapacityCount(storageCapacities);
        }

        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("8");
        record.setWorkTableName("zz_general_certificate");
        record.setWorkId(generalCertificate.getId());
        record.setWorkNo(generalCertificate.getCertificateNo());
        record.setCertificateName(generalCertificate.getCertificateName());
        record.setCertificateCode(generalCertificate.getCertificateNo());
        record.setSignOrgId(generalCertificate.getSignOrgId());
        record.setSignOrgName(generalCertificate.getSignOrgName());
        record.setCertificateType(generalCertificate.getCertificateType());
        record.setRemarks("证书中心：" + generalCertificate.getCertificateNo() + "入库");
        systemRecordService.save(record);
    }

    /**
     * 根据id查询证书信息
     *
     * @param id
     * @return
     */
    public GeneralCertificate findCredentialById(Long id) {
        GeneralCertificate generalCertificate = generalCertificateDao.queryGertificateInfoById(id);
        generalCertificate.setPersonalPhone(net.dgg.iboss.base.util.StringUtils.encryptionNumber(desUtil.decrypt(generalCertificate.getPersonalPhone())));
        return generalCertificate;
    }


    /**
     * 退回证书重新入库
     *
     * @param generalCertificate
     * @param params
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<StorageCapacity> UpdateReturnCertificate(GeneralCertificate generalCertificate, Map params) throws ParseException {
        UserEntity user = sessionManager.getCurrentUser();

        // 设置证书其他值
        generalCertificate.setCertificateExpiryTime(params.containsKey("certificateExpiryTimes") && StringUtils.isNotEmpty(params.get("certificateExpiryTimes")) ? DateUtils.stringToDate(params.get("certificateExpiryTimes").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setCertificateToThreeTime(params.containsKey("certificateToThreeTimes") && StringUtils.isNotEmpty(params.get("certificateToThreeTimes")) ? DateUtils.stringToDate(params.get("certificateToThreeTimes").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setCompanyContractExpireTime(params.containsKey("companyContractExpireTimes") && StringUtils.isNotEmpty(params.get("companyContractExpireTimes")) ? DateUtils.stringToDate(params.get("companyContractExpireTimes").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setContractSigningTime(params.containsKey("contractSigningTimes") && StringUtils.isNotEmpty(params.get("contractSigningTimes")) ? DateUtils.stringToDate(params.get("contractSigningTimes").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setTalentContractExpireTime(params.containsKey("talentContractExpireTimes") && StringUtils.isNotEmpty(params.get("talentContractExpireTimes")) ? DateUtils.stringToDate(params.get("talentContractExpireTimes").toString(), "yyyy-MM-dd") : null);
        generalCertificate.setDepositPayTime(params.containsKey("depositPayTimes") && StringUtils.isNotEmpty(params.get("depositPayTimes")) ? DateUtils.stringToDate(params.get("depositPayTimes").toString(), "yyyy-MM-dd HH:mm:ss") : null);
        generalCertificate.setDepositPayTime(params.containsKey("tailMoneyPayTimes") && StringUtils.isNotEmpty(params.get("tailMoneyPayTimes")) ? DateUtils.stringToDate(params.get("tailMoneyPayTimes").toString(), "yyyy-MM-dd HH:mm:ss") : null);
        Map<String, String> map = baseCredentialService.dealArea(params.get("areaName").toString(), generalCertificate.getCertificateArea());
        if (StringUtils.isNotEmpty(map)) { // 如果用户选择的是省/市
            generalCertificate.setAreaProvince(map.get("pcode").toString());
        } else { // 如果只选择了省
            generalCertificate.setAreaProvince(generalCertificate.getCertificateArea());
            generalCertificate.setCertificateArea(null);
        }

        // 证书默认不超期
        generalCertificate.setOverdueStatus("1");
        String certificateSpecialties = params.containsKey("certificateSpecialty") ? params.get("certificateSpecialty").toString() : null;
        Long[] certificateSpecialtys = (Long[]) ConvertUtils.convert(certificateSpecialties.split(","), Long.class);

        // 验证证书编号
        baseCredentialService.checkCredentialNo(params);

        List<StorageCapacity> storageCapacities = null;

        generalCertificate.setCertificateEntryTime(new Date());

        // 验证证书关联的生产订单状态
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(generalCertificate.getScOrderId());
        ValidateUtils.isTrue(StringUtils.isNotEmpty(productOrder) && !productOrder.getStatus().equals(ScProductConstant.SC_ORDER_OVER_CERTIFICATE), CertificateExcption.class, "该销售子订单绑定的生产订单已完结，证书已经入库！");

        // 证书状态：入库
        generalCertificate.setLibraryStatus(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN);
        generalCertificate.setLastWarehousingTime(new Date());

        commonService.updateScProductOrderStatus(generalCertificate.getScOrderId());

        CertificateProduct certificateProduct = certificateProductService.saveCertifateProduct(generalCertificate.getId(), generalCertificate.getScOrderId(), 1);
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("1");
        systemRecord.setOperateType("1");
        systemRecord.setWorkId(certificateProduct.getId());
        systemRecord.setWorkNo(certificateProduct.getScOrderNo());
        systemRecord.setWorkTableName("zz_certificate_product");
        systemRecord.setCertificateType(generalCertificate.getCertificateType());
        systemRecord.setCertificateCode(generalCertificate.getCertificateNo());
        systemRecord.setCertificateName(generalCertificate.getCertificateName());
        systemRecord.setSignOrgId(generalCertificate.getSignOrgId());
        systemRecord.setSignOrgName(generalCertificate.getSignOrgName());
        systemRecord.setRemarks("证书中心：证书绑定生产订单");
        systemRecordService.save(systemRecord);

        // 证书状态默认为未使用
        generalCertificate.setCertificateStatus(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);

        // 新增证书
        generalCertificate.setCreateUser(user);

        generalCertificate.setScOrderNo(null);
        generalCertificate.setScOrderId(null);

        // 修改证书信息
        baseCredentialDao.updateByPrimaryKey(generalCertificate);
        generalCertificateDao.updateByPrimaryKey(generalCertificate);

        // 修改证书关联销售子订单状态
        Product product = productService.selectByPrimaryKey(Long.parseLong(params.get("productId").toString()));
        product.setRelevanceCredential(1);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(product), CertificateExcption.class, "该证书绑定的销售子订单不存在，请核对后进行添加！");
        productService.updateProduct(product);

        // 验证证书类型并将证书绑定证书基本类型
        GeneralCertificate oldGeneralCertificate = generalCertificateDao.selectByPrimaryKey(generalCertificate.getId());
        storageCapacities = verificationStorageCapacityAndBoundV2(generalCertificate.getId(), params, true, oldGeneralCertificate);

        // 保存操作日志
        SystemRecord systemRecords = new SystemRecord();
        systemRecords.setSource("1");
        systemRecords.setOperateType("8");
        systemRecords.setWorkTableName("zz_general_certificate");
        systemRecords.setWorkId(generalCertificate.getId());
        systemRecords.setWorkNo(generalCertificate.getCertificateNo());
        systemRecords.setCertificateName(generalCertificate.getCertificateName());
        systemRecords.setCertificateCode(generalCertificate.getCertificateNo());
        systemRecords.setSignOrgId(generalCertificate.getSignOrgId());
        systemRecords.setSignOrgName(generalCertificate.getSignOrgName());
        systemRecords.setCertificateType(generalCertificate.getCertificateType());
        systemRecords.setRemarks("证书中心：退回证书重新入库");
        systemRecordService.save(systemRecords);
        return storageCapacities;
    }

    /**
     * 根据证书编号查询证书信息
     *
     * @param certificateNo
     * @return
     */
    public GeneralCertificate findCredentialByNo(String certificateNo) {
        return generalCertificateDao.findCredentialByNo(certificateNo);
    }

    /**
     * 根据证书id查询证书绑定的最新的销售子订单信息(非资质生产订单绑定)
     *
     * @param id
     * @return
     */
    public Map findOrderBusinessInfoByCertificate(Long id) {
        Map businessOrder = generalCertificateDao.findOrderBusinessInfoByCertificate(id);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(businessOrder) && businessOrder.size() > 0, CertificateExcption.class, "您选择的证书没有绑定销售子订单，不能进行费用申请！");
        return businessOrder;
    }

    /**
     * 证书总览：证书信息统计
     *
     * @param params
     * @return
     */
    public Map generalCredentialCount(Map params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        params.put("noUse", CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE);
        params.put("reservation", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION);
        params.put("return", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        params.put("subordinate", CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE);
        params.put("local", CredentialConstant.LOCAL);
        params.put("nationwide", CredentialConstant.NATIONWIDE);
        params.put("libraryStatus", CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN);
        params.put("subordinateOverDue", CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_AFFILIATED);
        params.put("companyOverDue", CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_COMPANY);
        params.put("talentOverDue", CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_TALENTS);
        params.put("credentialOverDue", CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL);
        return generalCertificateDao.generalCredentialCount(params);
    }

    /**
     * 根据id查询证书信息:编译
     *
     * @param id
     * @return
     */
    public GeneralCertificate findCredentialByIdWithTranslate(Long id) {
        GeneralCertificate generalCertificate = generalCertificateDao.queryGertificateById(id);
        generalCertificate.setPersonalPhone(net.dgg.iboss.base.util.StringUtils.encryptionNumber(desUtil.decrypt(generalCertificate.getPersonalPhone())));
        String[] column = {"certificateCategory", "certificateToThree", "libraryStatus", "certificateStatus", "certificateArea", "applicationScope", "areaProvince", "certificateLevel"};
        return translateUtil.translateObject(column, generalCertificate);
    }


    /**
     * 根据生产订单id查询证书
     *
     * @param scProductOrderId
     * @return
     */
    public GeneralCertificate findCredentialByScOrderId(Long scProductOrderId) {
        return generalCertificateDao.queryGertificateInfoByScOrderId(scProductOrderId);
    }

    /**
     * 根据生产订单id查询证书数量
     *
     * @param scProductOrderId
     * @return
     */
    public int queryGertificateCountByScOrderId(Long scProductOrderId) {
        return generalCertificateDao.queryGertificateCountByScOrderId(scProductOrderId);
    }

    /*
     * @Author zsx
     * @Date 2018-10-23 10:10:44
     * @Description 证书全部导出
     * @param params
     * @return <AllGeneralCredentialVo>
     */
    public List<AllGeneralCredentialVo> queryExportAllCredential(Map params) {
        params.put("returnStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_RETURN);
        List<AllGeneralCredentialVo> generalCertificates = generalCertificateDao.queryExportAllCredential(params);
        String[] hideColum = {"personalPhone"};//解密
        generalCertificates = desUtil.decryptList(hideColum, generalCertificates);
        generalCertificates = CustomerNumberEncryptionUtil.encryptionList(hideColum, generalCertificates);
        String[] column = {"certificateCategory", "libraryStatus", "certificateStatus", "overdueType", "certificateArea", "areaProvince", "certificateStatus", "applicationScope", "certificateLevel","libraryStatus"};
        return translateUtil.translateList(column, generalCertificates);
    }


    /**
     * 判断证书过期类型是否是证书过期
     *
     * @return
     */
    public Boolean isCertificateOverDue(Long certificateId) {
        GeneralCertificate generalCertificate = generalCertificateDao.selectByPrimaryKey(certificateId);
        // 过期并且是过期类型包含证书过期
        if ("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL)) {
            return true;
        }
        return false;
    }

    /**
     * 普通证书绑定证书类型以及库容量计算v2.0
     *
     * @param id                    证书id
     * @param params                相关参数
     * @param isBack                是否退回证书重新入库
     * @param oldGeneralCertificate 如果是修改证书信息需要转入修改前的证书信息
     * @return
     */
    @Transactional
    public List<StorageCapacity> verificationStorageCapacityAndBoundV2(Long id, Map params, Boolean isBack, GeneralCertificate oldGeneralCertificate) {

        ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");

        // 验证证书专业是否已经绑定证书基础类型
        List<StorageCapacity> allList = storageCapacityService.verificationStorageCapacity(params);
        if (StringUtils.isNotEmpty(allList) && allList.size() > 0) {
            // 查询证书信息
            GeneralCertificate generalCertificate = generalCertificateDao.selectByPrimaryKey(id);
            // 新增证书
            if (StringUtils.isEmpty(generalCertificate)) {
                CertificateSpecialty certificateSpecialty = null;
                for (StorageCapacity storageCapacity : allList) {
                    certificateSpecialty = new CertificateSpecialty();
                    certificateSpecialty.setCertificateCode(storageCapacity.getCertificateCode());
                    certificateSpecialty.setCertificateSpecialtyId(storageCapacity.getCertificateMajorId());
                    certificateSpecialty.setCertificateTypeId(storageCapacity.getCertificateTypeId());
                    certificateSpecialty.setCertificateId(id);
                    certificateSpecialty.setId(DggKeyWorker.nextId());
                    certificateSpecialty.setType(params.containsKey("generalType") && params.get("generalType").toString().equals(CredentialConstant.ZZ_CREDENTIAL) ? CredentialConstant.ZZ_CREDENTIAL : CredentialConstant.GENERAL_CREDENTIAL);
                    certificateSpecialtyService.insert(certificateSpecialty);
                }
                // 修改库容 在库容量+1
                for (StorageCapacity storageCapacity : allList) {
                    storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                }

                storageCapacityService.updateStorageCapacityCount(allList);
            } else { // 修改证书
                ValidateUtils.isTrue(StringUtils.isNotEmpty(oldGeneralCertificate), CertificateExcption.class, "修改前的证书信息不能为空！");

                // 证书基本类型信息是否更改
                Boolean isChangeType = true;

                //
                List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(id);
                if (StringUtils.isNotEmpty(certificateSpecialties) && certificateSpecialties.size() > 0) {

                    List<String> codes = new ArrayList<>();
                    String oldCodes = "_";
                    for (CertificateSpecialty certificateSpecialty : certificateSpecialties) {
                        codes.add(certificateSpecialty.getCertificateCode());
                        oldCodes += certificateSpecialty.getCertificateCode() + "_";
                    }

                    // 判断证书基本类型是否做了更改
                    if (allList.size() == certificateSpecialties.size()) {
                        for (StorageCapacity storageCapacity : allList) {
                            if (oldCodes.contains("_" + storageCapacity.getCertificateCode() + "_")) {
                                isChangeType = false;
                            } else {
                                isChangeType = true;
                                break;
                            }
                        }
                    }

                    // 判断修改前证书是否过期并且判断是否是证书过期
                    Boolean isOldCertificateOverDue = "0".equals(oldGeneralCertificate.getOverdueStatus()) && oldGeneralCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL);
                    Boolean isCertificateOverDue = "0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL);
                    // 判断是否未使用
                    Boolean isNoUse = CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(generalCertificate.getLibraryStatus()) && CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(generalCertificate.getCertificateStatus());

                    // 如果证书基本类型做了修改
                    if (isChangeType) {
                        // 查询修改前证书绑定的基本类型信息
                        List<StorageCapacity> storageCapacitysByCodes = storageCapacityService.findStorageCapacitysByCodes(codes);

                        // 如果证书状态不为在库未使用
                        if (!isNoUse) {
                            // 已预订 原预定量 -1
                            if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(generalCertificate.getCertificateStatus())) {
                                // 原基本类型预定量-1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setReserveNumbers(storageCapacitysByCode.getReserveNumbers().intValue() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                                allList = storageCapacityService.findStorageCapacitys(params);
                                // 现基本类型预定量+1
                                for (StorageCapacity storageCapacitysByCode : allList) {
                                    storageCapacitysByCode.setReserveNumbers(storageCapacitysByCode.getReserveNumbers().intValue() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(allList);

                            } else if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(generalCertificate.getCertificateStatus())) { // 已匹配

                                // 原匹配量 -1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setMatchNumbers(storageCapacitysByCode.getMatchNumbers().intValue() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);

                                allList = storageCapacityService.findStorageCapacitys(params);
                                // 现匹配量 +1
                                for (StorageCapacity storageCapacitysByCode : allList) {
                                    storageCapacitysByCode.setMatchNumbers(storageCapacitysByCode.getMatchNumbers().intValue() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(allList);

                            } else if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE.equals(generalCertificate.getCertificateStatus())) { // 已使用

                                // 原使用量 -1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setHangUpNumbers(storageCapacitysByCode.getHangUpNumbers().intValue() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);

                                allList = storageCapacityService.findStorageCapacitys(params);
                                // 现使用量 +1
                                for (StorageCapacity storageCapacitysByCode : allList) {
                                    storageCapacitysByCode.setHangUpNumbers(storageCapacitysByCode.getHangUpNumbers().intValue() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(allList);
                            }
                        } else {

                            // 证书以前不存在超期情况并且编辑后证书不存在证书过期情况
                            if (!isOldCertificateOverDue && !isCertificateOverDue) {
                                // 原在库量 -1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers().intValue() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                            }
                            allList = storageCapacityService.findStorageCapacitys(params);

                            // 编辑保存的证书不存在证书超期情况
                            if (!isCertificateOverDue) {
                                // 现在库量 +1
                                for (StorageCapacity storageCapacitysByCode : allList) {
                                    storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers().intValue() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(allList);
                            }
                        }

                        // 删除证书绑定的证书专业中间表数据
                        certificateSpecialtyService.deleteByCertificateId(id);
                        // 绑定证书与基本类型中间表数据
                        CertificateSpecialty certificateSpecialty = null;
                        for (StorageCapacity storageCapacity : allList) {
                            certificateSpecialty = new CertificateSpecialty();
                            certificateSpecialty.setCertificateCode(storageCapacity.getCertificateCode());
                            certificateSpecialty.setCertificateSpecialtyId(storageCapacity.getCertificateMajorId());
                            certificateSpecialty.setCertificateTypeId(storageCapacity.getCertificateTypeId());
                            certificateSpecialty.setCertificateId(id);
                            certificateSpecialty.setId(DggKeyWorker.nextId());
                            certificateSpecialty.setType(params.containsKey("generalType") && params.get("generalType").toString().equals(CredentialConstant.ZZ_CREDENTIAL) ? CredentialConstant.ZZ_CREDENTIAL : CredentialConstant.GENERAL_CREDENTIAL);
                            certificateSpecialtyService.insert(certificateSpecialty);
                        }

                    } else {//如果证书类型没有做更改
                        // 修改前证书超期，修改后证书未超期 证书基本类型库容量+1 因为定时器跑过期数据时减去了库容所以现在需要加回来
                        // 证书重新入库需要库容需要 +1
                        if ((isOldCertificateOverDue && "1".equals(generalCertificate.getOverdueStatus())) || isBack || (isOldCertificateOverDue && !isCertificateOverDue)) {
                            if (isNoUse) { // 状态为在库未使用才会进行库容+1
                                for (StorageCapacity storageCapacitysByCode : allList) {
                                    storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers().intValue() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(allList);
                            }
                        }
                    }
                }
            }
        }
        allList = storageCapacityService.findStorageCapacitys(params);
        return allList;
    }

    /*
     * @Author zsx
     * @Date 2018-10-24 09:10:29
     * @Description 资质证书绑定证书类型及库容量计算v3 (前期未抽取方法)
     * @param id 资质证书id
     * @param params
     * @param baseCredential 资质原始基本数据
     * @return List<StorageCapacity>
     */
    @Transactional
    public List<StorageCapacity> verificationStorageCapacityAndBoundV3(Long id, Map params, BaseCredential baseCredential) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "资质证书id不能为空");
        // 验证证书专业是否已经绑定证书基础类型
        List<StorageCapacity> capacities = storageCapacityService.verificationStorageCapacity(params);

        if (StringUtils.isNotEmpty(capacities) && capacities.size() > 0) {
            BaseCredential credential = baseCredentialService.selectByPrimaryKey(id);
            // 新增资质
            if (StringUtils.isEmpty(baseCredential)) {
                //添加中间表(后期改批量插入)
                CertificateSpecialty certificateSpecialty = null;
                for (StorageCapacity storageCapacity : capacities) {
                    certificateSpecialty = new CertificateSpecialty();
                    certificateSpecialty.setCertificateId(id);
                    certificateSpecialty.setCertificateCode(storageCapacity.getCertificateCode());
                    certificateSpecialty.setCertificateSpecialtyId(storageCapacity.getCertificateMajorId());
                    certificateSpecialty.setCertificateTypeId(storageCapacity.getCertificateTypeId());
                    certificateSpecialty.setId(DggKeyWorker.nextId());
                    certificateSpecialty.setType(params.containsKey("generalType") && params.get("generalType").toString().equals(CredentialConstant.ZZ_CREDENTIAL) ? CredentialConstant.ZZ_CREDENTIAL : CredentialConstant.GENERAL_CREDENTIAL);
                    certificateSpecialtyService.insert(certificateSpecialty);
                }
                // 修改库容 在库容量+1
                for (StorageCapacity storageCapacity : capacities) {
                    storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                }
                storageCapacityService.updateStorageCapacityCount(capacities);
            } else {
                //修改资质
                ValidateUtils.isTrue(StringUtils.isNotEmpty(baseCredential), CertificateExcption.class, "修改前的资质信息不能为空！");
                List<CertificateSpecialty> certificateSpecialties = certificateSpecialtyService.findCertificateSpecialtyByCertificateId(id);
                if (null != certificateSpecialties && certificateSpecialties.size() > 0) {
                    //资质类型信息是否更改
                    Boolean isChangeStatus = true;
                    List<String> codes = new ArrayList<>();
                    Map<String, String> codeMap = new HashMap<>();
                    for (CertificateSpecialty certificateSpecialty : certificateSpecialties) {
                        codes.add(certificateSpecialty.getCertificateCode());
                        codeMap.put(certificateSpecialty.getCertificateCode(), certificateSpecialty.getCertificateCode());
                    }
                    // 判断资质基本类型是否做了更改
                    if (capacities.size() == certificateSpecialties.size()) {
                        for (StorageCapacity storageCapacity : capacities) {
                            if (null != codeMap.get(storageCapacity.getCertificateCode())) {
                                isChangeStatus = false;
                            } else {
                                isChangeStatus = true;
                                break;
                            }
                        }
                    }
                    //如果类型修改了
                    if (isChangeStatus) {
                        // 查询修改前资质绑定的基本类型信息
                        List<StorageCapacity> storageCapacitysByCodes = storageCapacityService.findStorageCapacitysByCodes(codes);
                        // 如果资质状态不为未使用状态
                        if (!CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE.equals(credential.getCertificateStatus())) {
                            // 已预订 原预定量 -1
                            if (CredentialConstant.CERTIFICATE_APTITUDE_STATUS_TWO.equals(credential.getCertificateStatus())) {
                                // 原基本类型预定量-1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setReserveNumbers(storageCapacitysByCode.getReserveNumbers() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                                capacities = storageCapacityService.findStorageCapacitys(params);
                                // 现基本类型预定量+1
                                for (StorageCapacity storageCapacitysByCode : capacities) {
                                    storageCapacitysByCode.setReserveNumbers(storageCapacitysByCode.getReserveNumbers() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(capacities);

                            } else if (CredentialConstant.CERTIFICATE_APTITUDE_STATUS_THREE.equals(credential.getCertificateStatus()) ||
                                    CredentialConstant.CERTIFICATE_APTITUDE_STATUS_FOUR.equals(credential.getCertificateStatus())) { // 已匹配或者已申请准让
                                // 原匹配量 -1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setMatchNumbers(storageCapacitysByCode.getMatchNumbers() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);

                                capacities = storageCapacityService.findStorageCapacitys(params);
                                // 现匹配量 +1
                                for (StorageCapacity storageCapacitysByCode : capacities) {
                                    storageCapacitysByCode.setMatchNumbers(storageCapacitysByCode.getMatchNumbers() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(capacities);
                            }
                        } else {
                            // 编辑前后均为超期
                            if (CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(credential.getOverdueStatus()) && CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(baseCredential.getOverdueStatus())) {
                                // 原在库量 -1
                                for (StorageCapacity storageCapacitysByCode : storageCapacitysByCodes) {
                                    storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers() - 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(storageCapacitysByCodes);
                            }
                            capacities = storageCapacityService.findStorageCapacitys(params);

                            // 未超期在库量+1
                            if (CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(credential.getOverdueStatus())) {
                                // 现在库量 +1
                                for (StorageCapacity storageCapacitysByCode : capacities) {
                                    storageCapacitysByCode.setLibraryNumbers(storageCapacitysByCode.getLibraryNumbers() + 1);
                                }
                                storageCapacityService.updateStorageCapacityCount(capacities);
                            }
                        }
                        // 删除资质绑定的资质专业中间表数据
                        certificateSpecialtyService.deleteByCertificateId(id);
                        // 绑定资质与基本类型中间表数据
                        CertificateSpecialty certificateSpecialty = null;
                        for (StorageCapacity storageCapacity : capacities) {
                            certificateSpecialty = new CertificateSpecialty();
                            certificateSpecialty.setCertificateId(id);
                            certificateSpecialty.setId(DggKeyWorker.nextId());
                            certificateSpecialty.setCertificateCode(storageCapacity.getCertificateCode());
                            certificateSpecialty.setCertificateSpecialtyId(storageCapacity.getCertificateMajorId());
                            certificateSpecialty.setCertificateTypeId(storageCapacity.getCertificateTypeId());
                            certificateSpecialty.setType(params.containsKey("generalType") && params.get("generalType").toString().equals(CredentialConstant.ZZ_CREDENTIAL) ? CredentialConstant.ZZ_CREDENTIAL : CredentialConstant.GENERAL_CREDENTIAL);
                            certificateSpecialtyService.insert(certificateSpecialty);
                        }
                    } else {
                        // 如果资质类型没有做更改且未使用且修改前资质超期，修改后资质未超期 在库量+1
                        if (CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(credential.getOverdueStatus()) && CredentialConstant.CERTIFICATE_APTITUDE_EXCEED_ONE.equals(baseCredential.getOverdueStatus())
                                && CredentialConstant.CERTIFICATE_APTITUDE_STATUS_ONE.equals(baseCredential.getCertificateStatus())) {
                            for (StorageCapacity storageCapacity : capacities) {
                                storageCapacity.setLibraryNumbers(storageCapacity.getLibraryNumbers() + 1);
                            }
                            storageCapacityService.updateStorageCapacityCount(capacities);
                        }
                    }

                }
            }
        }
        capacities = storageCapacityService.findStorageCapacitys(params);
        return capacities;
    }

    /**
     * 取消证书当前状态（只能是使用/匹配/预订状态可以取消匹配）
     *
     * @param certificateId
     */
    public void cancelCertificateStatus(Long certificateId,String certificateNo) {
        ValidateUtils.isTrue(StringUtils.isNotEmpty(certificateId), CertificateExcption.class, "证书id不能为空");
        GeneralCertificate generalCertificate = generalCertificateDao.selectByPrimaryKey(certificateId);
        ValidateUtils.isTrue(StringUtils.isNotEmpty(generalCertificate), CertificateExcption.class, "证书不存在");
        ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(generalCertificate.getCertificateStatus())
                || CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE.equals(generalCertificate.getCertificateStatus())
                || CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(generalCertificate.getCertificateStatus()), CertificateExcption.class, "证书未使用或已退回，不能对当前状态进行更改！");
        Map<String, Object> param = new HashMap<>();
        param.put("certificateId", generalCertificate.getBaseId());
        param.put("scOrderId", generalCertificate.getScOrderId());
        param.put("type", 1);
        param.put("certificateNo", certificateNo);

        // 保存操作日志 基础表的
        SystemRecord baseSystemRecord = new SystemRecord();
        baseSystemRecord.setSource("1");//生产
        baseSystemRecord.setOperateType("15");// 操作类型  取消使用
        baseSystemRecord.setWorkTableName("zz_base_credential");
        baseSystemRecord.setWorkId(certificateId);
        baseSystemRecord.setRemarks("证书取消使用");
        baseSystemRecord.setWorkNo(certificateNo);
        baseSystemRecord.setCertificateCode(certificateNo);
        systemRecordService.save(baseSystemRecord);
        //预订
        if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_RESERVATION.equals(generalCertificate.getCertificateStatus())) {
            zzInProcessService.cancelAdvanceCertificate(generalCertificate.getBaseId(),certificateNo, generalCertificate.getScOrderId(), 1);
        } else if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE.equals(generalCertificate.getCertificateStatus())) { // 使用
            zzInProcessService.cancelSubordinateCertificate(param);
        } else if (CredentialConstant.GENERAL_CREDENTIAL_STATUS_MATCH.equals(generalCertificate.getCertificateStatus())) { // 匹配
            zzInProcessService.cancelMatchCertificate(param);
        }

    }

    /*
     * @Author zsx
     * @Date 2018-11-13 03:11:05
     * @Description 证书使用
     */
    @Transactional
    public void saveCertificatesAttached(Map params){
        //为了流程通用  采用调用以前接口
        //预定资质
        zzInProcessService.saveCertificateAdvance(Long.parseLong(params.get("certificateId").toString()),null, Long.parseLong(params.get("scOrderId").toString()), 1);
        //匹配证书
        zzInProcessService.saveMatchCertificate(Long.parseLong(params.get("certificateId").toString()),null, Long.parseLong(params.get("scOrderId").toString()), 1);
        //使用证书
        zzInProcessService.saveCertificateSubordinate(params);
    }
    @Transactional
    public void updateGertificatePhone() {
        List<Map> list = generalCertificateDao.queryGertificateList();
        if(list.size()>0){
            for(Map map : list){
                Map newMap = new HashMap<>();
                if(null != map.get("personalPhone") || "" !=map.get("personalPhone")) {
                    newMap.put("generalCertificateId", map.get("generalCertificateId"));
                    newMap.put("personalPhone", desUtil.encrypt(map.get("personalPhone").toString()));
                    generalCertificateDao.updateGeneralCertificatePhone(newMap);
                }
            }
        }
    }

    public String getPersonalPhone(Long id){
        GeneralCertificate generalCertificate = generalCertificateDao.selectByPrimaryKey(id);
        return desUtil.decrypt(generalCertificate.getPersonalPhone());
    }

    /**
     * 查询入库列表
     * @param warehousing
     * @return
     */
    public List<Warehousing> getWarehousingList(Warehousing warehousing) {
        List<Warehousing> warehousingList = generalCertificateDao.getWarehousingList(warehousing);
        for (Warehousing warehousing1 : warehousingList) {
            String[] split = warehousing1.getCertificateSpecialtys().split(",");
            StringBuilder sb =new StringBuilder();
            for (String s : split) {
                String cerificateTypeName2 = certificateTypeDao.getCerificateTypeName2(Integer.parseInt(warehousing1.getCertificateType()), Integer.parseInt(s));
                sb.append(cerificateTypeName2).append(" ");
            }
            warehousing1.setCertificateSpecialtys(sb.toString());
            warehousing1.setCertificateType(certificateTypeDao.getCerificateTypeName1(Integer.parseInt(warehousing1.getCertificateType())));
            TreeBook treeBookByCode = treeBookService.getTreeBookByCode(warehousing1.getCertificateLevel());
            warehousing1.setCertificateLevel(treeBookByCode.getName());
        }
        return warehousingList;
    }

    /**
     * 查询入库列表总数
     * @param warehousing
     * @return
     */
    public int getCountWarehousingList(Warehousing warehousing) {
        return generalCertificateDao.getCountWarehousingList(warehousing);
    }

    public boolean addWarehousing2(Warehousing warehousing) {
        UserEntity user = sessionManager.getCurrentUser();
        warehousing.setCreaterId(user.getId());
        warehousing.setCreaterName(user.getRealName());
        warehousing.setUpdateName(user.getRealName());
        warehousing.setUpdateTime(new Date());
        return generalCertificateDao.addWarehousing2(warehousing) > 0;
    }

    /**
     * 通过id查询入库信息
     * @param id
     * @return
     */
    public Warehousing findWarehousingById(Long id) {
        return generalCertificateDao.findWarehousingById(id);
    }

    /**
     * 保存修改
     * @param warehousing
     * @return
     */
    public boolean updateWarehousing(Warehousing warehousing) {
        UserEntity user = sessionManager.getCurrentUser();
        warehousing.setUpdateName(user.getRealName());
        warehousing.setUpdateTime(new Date());
        return generalCertificateDao.updateWarehousing(warehousing) > 0;
    }

    /**
     * 校验新增的入库信息是否存在
     * @param warehousing
     * @return
     */
    public boolean selectWarehousing(Warehousing warehousing) {
        return generalCertificateDao.selectWarehousing(warehousing) >0;
    }

    /**
     * 保存企业续签
     * @param params
     */
    @Transactional
    public void saveBusinessRenewal(Map params) throws ParseException {
        GeneralCertificate credential = this.findCredentialByIdWithTranslate(Long.parseLong(params.get("certificateId").toString()));
        credential.setAffiliatedCompany(params.get("affiliatedCompany").toString());
        credential.setCertificatePrice(new BigDecimal(params.get("certificatePrice").toString()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        credential.setAffiliatedStartTime(sdf.parse(params.get("affiliatedStartTime").toString()));
        credential.setAffiliatedExpireTime(sdf.parse(params.get("affiliatedExpireTime").toString()));
        // 关联生产订单
        credential.setScOrderId(Long.valueOf(params.get("scOrderId").toString()));
        credential.setScOrderNo(params.get("scOrderNo").toString());
        // 保存使用信息
        int saveGeneralCertificate = generalCertificateDao.saveGeneralCertificate(credential);
        // 保存价格
        int saveBaseCertificate = generalCertificateDao.saveBaseCertificate(credential);
        if (saveBaseCertificate ==0 || saveGeneralCertificate ==0){
            ValidateUtils.isTrue(true,CertificateExcption.class, "保存企业续签失败");
        }
        // 订单使用证书
        this.saveCertificatesAttached(params);
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("1");
        systemRecord.setOperateType("59");
        systemRecord.setWorkTableName("zz_general_certificate");
        systemRecord.setWorkId(credential.getId());
        systemRecord.setWorkNo(credential.getScOrderNo());
        systemRecord.setCertificateCode(credential.getCertificateNo());
        systemRecord.setSignOrgId(credential.getSignOrgId());
        systemRecord.setSignOrgName(credential.getSignOrgName());
        systemRecord.setCertificateType(credential.getCertificateType());
        systemRecord.setCertificateCode(credential.getCertificateNo());
        systemRecord.setCertificateName(credential.getCertificateName());
        systemRecord.setRemarks("企业续签:使用公司："+params.get("affiliatedCompany").toString()+"使用金额："+params.get("certificatePrice").toString()+"使用开始时间:"+params.get("affiliatedStartTime").toString()+"使用结束时间："+params.get("affiliatedExpireTime").toString());
        systemRecordService.save(systemRecord);
    }

    /**
     * 修改证书状态
     * @param ids
     */
    @Transactional
    public void updateCertificateStatus(String ids) throws Exception {
        if(StringUtils.isEmpty(ids)){
            throw new CommonExcption("至少选择一条数据！");
        }
        Map params = new HashMap();
        JSONArray jsonArray = JSONArray.parseArray(ids);
        List<Long> idArray = jsonArray.toJavaList(Long.class);
        params.put("ids",idArray);
        generalCertificateDao.updateCertificateStatus(params);
        generalCertificateDao.updateCertificateStatusByGeneralType();
        //在库可用量
        List<Map> storageCapacityList = generalCertificateDao.selectStorageCapacityCount();
        if(!CollectionUtils.isEmpty(storageCapacityList)){
            generalCertificateDao.updateCertificateStatusByCertificateCode(storageCapacityList);
        }
        Thread.sleep(1000L);
        //预订
        List<Map> CertificateStatusByReservationList = generalCertificateDao.selectCertificateStatusCount("GENERAL_CREDENTIAL_STATUS_02");
        if(!CollectionUtils.isEmpty(CertificateStatusByReservationList)){
            generalCertificateDao.updateCertificateStatusByReservation(CertificateStatusByReservationList);
        }
        Thread.sleep(1000L);
        //匹配
        List<Map> CertificateStatusByMatchingList = generalCertificateDao.selectCertificateStatusCount("GENERAL_CREDENTIAL_STATUS_05");
        if(!CollectionUtils.isEmpty(CertificateStatusByMatchingList)){
            generalCertificateDao.updateCertificateStatusByMatching(CertificateStatusByMatchingList);
        }
        Thread.sleep(1000L);
        //挂靠
        List<Map> CertificateStatusByAffiliatedList = generalCertificateDao.selectCertificateStatusCount("GENERAL_CREDENTIAL_STATUS_03");
        if(!CollectionUtils.isEmpty(CertificateStatusByAffiliatedList)){
            generalCertificateDao.updateCertificateStatusByAffiliated(CertificateStatusByAffiliatedList);
        }
        Thread.sleep(1000L);
       //  保存操作日志 基础表的
        for(Long id :idArray){
            GeneralCertificate gc = generalCertificateDao.selectByPrimaryKey(id);
            SystemRecord baseSystemRecord = new SystemRecord();
            baseSystemRecord.setSource("1");//生产
            baseSystemRecord.setOperateType("65");// 操作类型  取消使用
            baseSystemRecord.setWorkTableName("zz_general_certificate");
            baseSystemRecord.setWorkId(id);
            baseSystemRecord.setRemarks("证书状态变更");
            baseSystemRecord.setWorkNo(gc.getCertificateNo());
            baseSystemRecord.setCertificateCode(gc.getCertificateNo());
            systemRecordService.save(baseSystemRecord);
        }
    }
}
